package com.example.mydy.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.example.mydy.MyDyApplication;
import com.example.mydy.model.Advertisement;
import com.example.mydy.model.Task;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CacheUtils {
    private static final String TAG = "CacheUtils";
    private static final String CACHE_PREFS_NAME = "MyDyCache";
    private static final String KEY_ADS_CACHE = "advertisements_cache";
    private static final String KEY_TASKS_CACHE = "tasks_cache";
    private static final String KEY_ANNOUNCEMENTS_CACHE = "announcements_cache";
    private static final String KEY_PROJECTS_CACHE = "projects_cache";
    private static final String KEY_REWARDS_CACHE = "rewards_cache";
    private static final long CACHE_EXPIRY_TIME = 24 * 60 * 60 * 1000; // 24小时

    // 使用Gson进行对象序列化和反序列化
    private static final Gson gson = new Gson();

    /**
     * 获取缓存SharedPreferences
     */
    private static SharedPreferences getCachePrefs(Context context) {
        return context.getSharedPreferences(CACHE_PREFS_NAME, Context.MODE_PRIVATE);
    }

    /**
     * 缓存广告列表
     */
    public static void cacheAdvertisements(Context context, List<Advertisement> advertisements) {
        if (advertisements == null || advertisements.isEmpty()) {
            Log.w(TAG, "尝试缓存空的广告列表");
            return;
        }

        try {
            SharedPreferences prefs = getCachePrefs(context);
            SharedPreferences.Editor editor = prefs.edit();
            
            // 序列化广告列表
            String adsJson = gson.toJson(advertisements);
            
            // 保存序列化的数据和缓存时间
            editor.putString(KEY_ADS_CACHE, adsJson);
            editor.putLong(KEY_ADS_CACHE + "_time", System.currentTimeMillis());
            
            boolean success = editor.commit();
            Log.d(TAG, "缓存广告列表 " + (success ? "成功" : "失败") + ", 共 " + advertisements.size() + " 条");
        } catch (Exception e) {
            Log.e(TAG, "缓存广告列表失败", e);
        }
    }

    /**
     * 获取缓存的广告列表
     */
    public static List<Advertisement> getCachedAdvertisements(Context context) {
        try {
            SharedPreferences prefs = getCachePrefs(context);
            String adsJson = prefs.getString(KEY_ADS_CACHE, null);
            long cacheTime = prefs.getLong(KEY_ADS_CACHE + "_time", 0);
            
            // 检查缓存是否存在且未过期
            if (adsJson != null && !adsJson.isEmpty() && !isCacheExpired(cacheTime)) {
                // 解析JSON
                Type listType = new TypeToken<ArrayList<Advertisement>>(){}.getType();
                List<Advertisement> ads = gson.fromJson(adsJson, listType);
                
                if (ads != null && !ads.isEmpty()) {
                    Log.d(TAG, "从缓存加载 " + ads.size() + " 条广告");
                    return ads;
                }
            }
            
            // 缓存为空或已过期
            Log.d(TAG, "广告缓存为空或已过期");
            return null;
        } catch (Exception e) {
            Log.e(TAG, "获取缓存广告列表失败", e);
            return null;
        }
    }

    /**
     * 检查缓存是否过期
     */
    private static boolean isCacheExpired(long cacheTime) {
        return System.currentTimeMillis() - cacheTime > CACHE_EXPIRY_TIME;
    }

    /**
     * 清除所有缓存
     */
    public static void clearAllCache(Context context) {
        try {
            SharedPreferences prefs = getCachePrefs(context);
            SharedPreferences.Editor editor = prefs.edit();
            editor.clear();
            boolean success = editor.commit();
            Log.d(TAG, "清除所有缓存 " + (success ? "成功" : "失败"));
        } catch (Exception e) {
            Log.e(TAG, "清除缓存失败", e);
        }
    }

    /**
     * 清除特定类型的缓存
     */
    public static void clearCache(Context context, String cacheKey) {
        try {
            SharedPreferences prefs = getCachePrefs(context);
            SharedPreferences.Editor editor = prefs.edit();
            editor.remove(cacheKey);
            editor.remove(cacheKey + "_time");
            boolean success = editor.commit();
            Log.d(TAG, "清除 " + cacheKey + " 缓存 " + (success ? "成功" : "失败"));
        } catch (Exception e) {
            Log.e(TAG, "清除缓存失败", e);
        }
    }

    private static final String PREF_NAME = "mydy_cache";
    private static final String KEY_ADVERTISEMENTS = "advertisements";
    private static final String KEY_USER_REWARDS = "user_rewards";
    private static final String KEY_LAST_UPDATE = "last_update";
    private static final long CACHE_EXPIRY = 5 * 60 * 1000; // 5分钟缓存过期

    private static SharedPreferences getPrefs(Context context) {
        return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    }

    public static void saveAdvertisements(Context context, List<Advertisement> advertisements) {
        SharedPreferences prefs = getPrefs(context);
        Gson gson = new Gson();
        String json = gson.toJson(advertisements);
        prefs.edit()
            .putString(KEY_ADVERTISEMENTS, json)
            .putLong(KEY_LAST_UPDATE, System.currentTimeMillis())
            .apply();
    }

    public static List<Map<String, Object>> getAdvertisements(Context context) {
        SharedPreferences prefs = getPrefs(context);
        String json = prefs.getString(KEY_ADVERTISEMENTS, null);
        if (json == null) return null;

        Gson gson = new Gson();
        Type type = new TypeToken<List<Map<String, Object>>>(){}.getType();
        return gson.fromJson(json, type);
    }

    public static void saveUserRewards(Context context, Map<String, Object> rewards) {
        SharedPreferences prefs = getPrefs(context);
        Gson gson = new Gson();
        String json = gson.toJson(rewards);
        prefs.edit()
            .putString(KEY_USER_REWARDS, json)
            .putLong(KEY_LAST_UPDATE, System.currentTimeMillis())
            .apply();
    }

    public static Map<String, Object> getUserRewards(Context context) {
        SharedPreferences prefs = getPrefs(context);
        String json = prefs.getString(KEY_USER_REWARDS, null);
        if (json == null) return null;

        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, Object>>(){}.getType();
        return gson.fromJson(json, type);
    }

    public static boolean isCacheExpired(Context context) {
        SharedPreferences prefs = getPrefs(context);
        long lastUpdate = prefs.getLong(KEY_LAST_UPDATE, 0);
        return System.currentTimeMillis() - lastUpdate > CACHE_EXPIRY;
    }

    public static void clearCache(Context context) {
        SharedPreferences prefs = getPrefs(context);
        prefs.edit().clear().apply();
    }

    /**
     * 缓存任务列表
     */
    public static void cacheTasks(Context context, List<Task> tasks) {
        if (tasks == null || tasks.isEmpty()) {
            Log.w(TAG, "尝试缓存空的任务列表");
            return;
        }

        try {
            SharedPreferences prefs = getCachePrefs(context);
            SharedPreferences.Editor editor = prefs.edit();
            
            // 序列化任务列表
            String tasksJson = gson.toJson(tasks);
            
            // 保存序列化的数据和缓存时间
            editor.putString(KEY_TASKS_CACHE, tasksJson);
            editor.putLong(KEY_TASKS_CACHE + "_time", System.currentTimeMillis());
            
            boolean success = editor.commit();
            Log.d(TAG, "缓存任务列表 " + (success ? "成功" : "失败") + ", 共 " + tasks.size() + " 条");
        } catch (Exception e) {
            Log.e(TAG, "缓存任务列表失败", e);
        }
    }

    /**
     * 获取缓存的任务列表
     */
    public static List<Task> getCachedTasks(Context context) {
        try {
            SharedPreferences prefs = getCachePrefs(context);
            String tasksJson = prefs.getString(KEY_TASKS_CACHE, null);
            long cacheTime = prefs.getLong(KEY_TASKS_CACHE + "_time", 0);
            
            // 检查缓存是否存在且未过期
            if (tasksJson != null && !tasksJson.isEmpty() && !isCacheExpired(cacheTime)) {
                // 解析JSON
                Type listType = new TypeToken<ArrayList<Task>>(){}.getType();
                List<Task> tasks = gson.fromJson(tasksJson, listType);
                
                if (tasks != null && !tasks.isEmpty()) {
                    Log.d(TAG, "从缓存加载 " + tasks.size() + " 个任务");
                    return tasks;
                }
            }
            
            // 缓存为空或已过期
            Log.d(TAG, "任务缓存为空或已过期");
            return null;
        } catch (Exception e) {
            Log.e(TAG, "获取缓存任务列表失败", e);
            return null;
        }
    }
} 